<template>
  <div class="jsonSchema-detail">
    <div class="jd-main w-full h-full">
      <div class="jd-main-container">
        <div class="jd-m-c-box" id="jd-m-c-box">
          <el-form ref="jsonSchemaFormRef" :model="jsonSchemaForm" label-width="0">
            <div class="jsonschema-main-title form-wrap flex flex-col">
              <div class="flex flex-row w-full" style="justify-content: space-between">
                <el-input v-model="jsonSchemaForm.modelDataName"
                  :placeholder="$t('tool.others.placehoderInput') + parentData.modelDataName + $t('tool.modelManage.chineseName')"></el-input>
                <div class="actions-wrap">
                  <el-button @click="handleSave">{{
                    $t("setup.buttonText.save")
                  }}</el-button>
                </div>
              </div>
              <div class="jd-m-c-b-actions flex items-center justify-start">
                <div>
                  <span>英文名称：</span>
                  <el-input v-model="jsonSchemaForm.dataEnglishName"
                    :style="{ width: $i18n.locale == 'zh' ? '195px' : '425px' }"></el-input>
                </div>
                <div style="margin-left: 5px">
                  <span>代号：</span>
                  <el-input readonly v-model="jsonSchemaForm.modelDataCode"
                    :placeholder="$t('tool.others.placehoderModelDataCode')"
                    :style="{ width: $i18n.locale == 'zh' ? '195px' : '425px' }"></el-input>
                </div>

                <!-- <el-button
                  class="jsonschema-btn"
                  @click="handleShowModelDetail"
                  >{{ $t("tool.modelManage.addModelDescription") }}</el-button
                > -->
              </div>
              <div class="set-model-detail" id="set-model-detail">
                <el-input id="set-model-detail-input" class="jtyj-set-mode-detail-input" type="textarea"
                  :placeholder="$t('tool.modelManage.modelDescriptionDetail')"
                  v-model="jsonSchemaForm.modelDataDescription"></el-input>
              </div>
            </div>
            <el-row>
              <el-col style="width: 100%; margin-top: 20px">
                <div class="jsonschema-main-content">
                  <div class="js-m-c-header flex justify-end flex-row">
                    <div class="js-m-c-h-btns">
                      <el-button class="jsonschema-btn" @click="handlePreviewJson">
                        <span role="img" class="appIcon">
                          <svg-icon icon-class="preview" width="16" height="16" />
                        </span>
                        {{ $t("tool.modelManage.preview") }}</el-button>
                      <el-button class="jsonschema-btn">
                        <span role="img" class="appIcon">
                          <svg-icon icon-class="generating" width="16" height="16" />
                        </span>
                        {{ $t("tool.modelManage.generating") }}</el-button>
                      <el-button class="jsonschema-btn" @click="handleShowJsonSchema">
                        <span role="img" class="appIcon">
                          <svg-icon icon-class="json" width="16" height="16" />
                        </span>
                        JSON Schema</el-button>
                    </div>
                  </div>
                  <div class="jsonschema-box" v-if="jsonSchemaForm.jsonSchemaData != null">
                    <JsonSchema ref="modelDataJsonSchemaRef" :currentName="$t('tool.modelManage.rootNode')"
                      :currentSchema.sync="jsonSchemaForm.jsonSchemaData" :curNode="curNode"
                      :parentSchema.sync="jsonSchemaForm.jsonSchemaData" :treeData="treeData" :isGlobalModule="false"
                      :globalTreeData="globalTreeData" :currentIndex="1" :writable="true" :isReadonly="false">
                    </JsonSchema>
                  </div>
                </div>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </div>
    <MonacoEditor ref="monacoEditorRef" :jsonSchemaData="jsonSchemaData" @confirm="handleMonacoConfirm">
    </MonacoEditor>
    <MonacoPreview ref="monacoPreviewRef" :currentJsonSchemaData="jsonSchemaData">
    </MonacoPreview>
  </div>
</template>

<script>
import {
  addModelData,
  updateModelData,
} from "@/api/myspace/model-manage-tool/model-manage";
import { mapState } from "vuex";
import JsonSchema from "./gradient.vue";
import MonacoEditor from "./monaco-editor.vue"
import MonacoPreview from "./monaco-preview.vue"
import jsonSchemaToolHandle from "@/utils/jsonSchema-tool.js";
export default {
  data() {
    return {
      code: "",
      nodeInfo: null,
      isAddModelData: false, // 是否是在新增数据建模，默认是
      isShowAlias: false, // 是否展示别名，默认不展示
      jsonSchemaForm: {},
      jsonSchemaData: "", // 传递给monaco的jsonSchemaData
      parentData: {
        modelDataName: ""
      }
    };
  },
  props: {
    modelId: {
      type: Number,
      default: null,
    },
    mainVersion: {
      type: Number,
      default: null,
    },
    curNode: {
      type: Object,
      default: undefined,
    },
    parentNode: {
      type: Object,
      default: undefined,
    },
    treeData: {
      type: Array,
      default: () => [],
    },
    globalTreeData: {
      type: Array,
      default: [],
    },
  },
  computed: {
    ...mapState({
      sharingMethodsOptions: (state) =>
        state.modelManageTool.sharingMethodsOptions,
    }),
  },
  components: {
    JsonSchema,
    MonacoEditor,
    MonacoPreview
  },
  watch: {
    curNode: {
      handler(newVal, oldVal) {
        this.nodeInfo = !newVal ? undefined : newVal.data;
        if (this.nodeInfo.nodeType == 1) {
          this.reset(false, this.nodeInfo);
        }
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    this.jsonSchemaTool = new jsonSchemaToolHandle(this);
    const _this = this;
    // 根据焦点事件与失去焦点事件，控制文本与输入框的切换显示
    // document.getElementById("title-compose").addEventListener("click", (e) => {
    //   handleDomClick(e.target);
    // });
    function handleDomClick(elementDom) {
      var inputDom = document.createElement("input");
      inputDom.id = "title-input";
      inputDom.className = "title-input";
      inputDom.style.padding = "0px";
      inputDom.setAttribute("autocomplete", "off");
      inputDom.value = elementDom.innerHTML.trim();
      inputDom.setAttribute(
        "placeholder",
        _this.$i18n.locale == "zh"
          ? "数据模型名称，建议使用代码模型名称或同义词"
          : "Model name, suggest using code model name or synonym"
      );
      elementDom.parentNode.replaceChild(inputDom, elementDom);
      document.getElementById("title-input").focus();
      inputDom.onblur = function () {
        elementDom.innerHTML = inputDom.value;
        _this.jsonSchemaForm.modelDataName = inputDom.value;
        inputDom.parentNode.replaceChild(elementDom, inputDom);
      };
      if (!_this.nodeInfo) {
        inputDom.focus(); //将焦点设置到该元素上
        let len = inputDom.value.length; // 获取当前文本长度
        inputDom.setSelectionRange(len, len); // 将光标定位到文本末尾
      }
    }
  },
  methods: {
    handleMonacoConfirm(content){
      console.log(content);
      this.jsonSchemaForm.jsonSchemaData = JSON.parse(content)
    },

    handleShowJsonSchema() {
      this.$refs.monacoEditorRef.openDialog()
      this.jsonSchemaData = JSON.stringify(this.jsonSchemaForm.jsonSchemaData, null, 8)
    },

    handlePreviewJson(){
      this.$refs.monacoPreviewRef.openDialog()
      this.jsonSchemaData = JSON.stringify(this.jsonSchemaForm.jsonSchemaData)

    },
    reset(flag, data) {
      this.isAddModelData = flag;
      if (data) {
        this.parentData = data
      } else {
        this.parentData = {
          modelDataName: ""
        }
      }
      if (flag) {
        this.jsonSchemaForm = {
          modelId: this.modelId, //模型id
          mainVersionId: this.mainVersion, //主版本
          modelDataId: null, //模型数据主键ID
          modelDataName: null, //模型中文名称
          modelDataCode: null, // 模型数据代号，自动生成
          parentId: this.parentNode.id, //模型父级ID
          nodeType: 1, //模型类型 tree_node_type类型：0文件，1文件夹
          modelDataType: this.parentNode.data.modelDataType, //类型 1指令/2事件/3型号属性/4额外属性/5目特属性
          modelDataDescription: "", //描述
          jsonSchemaData: {
            "type": "object",
            "properties": {},
            "x-apifox-orders": []
          }, //json schema数据
          userId: this.parentNode.data.userId, //创建人ID
        };
        if (!document.getElementById("title-compose")) return;
        document.getElementById("title-compose").click();
      } else {
        this.jsonSchemaForm = {
          ...data,
          modelId: this.modelId, //模型id
          mainVersionId: this.mainVersion, //主版本
          jsonSchemaData: JSON.parse(data.jsonSchemaData),
        };
      }
    },
    // 遍历获取 JSON Schema 中引用的 当前数据ID
    getReferencedIds(schema) {
      const referencedIds = new Set();
      const globalReferencedIds = new Set();
      function traverse(node) {
        if (typeof node === "object" && node !== null) {
          if (node.$ref) {
            const ref = node.$ref;
            if (ref.startsWith("#/definitions/")) {
              const id = ref.split("/").pop();
              referencedIds.add(id);
            }
            if (ref.startsWith("#/globalDefinitions/")) {
              const id = ref.split("/").pop();
              globalReferencedIds.add(id);
            }
          }
          for (const key in node) {
            traverse(node[key]);
          }
        }
      }

      traverse(schema);
      return {
        referencedIds: Array.from(referencedIds).join(","),
        globalReferencedIds: Array.from(globalReferencedIds).join(","),
      };
    },
    // 点击展示模型解释
    handleShowModelDetail() {
      document.getElementById("set-model-detail").style.display = "block";
      let inputDom = document.getElementById("set-model-detail-input");
      inputDom.focus(); //将焦点设置到该元素上
      let len = inputDom.value.length; // 获取当前文本长度
      inputDom.setSelectionRange(len, len); // 将光标定位到文本末尾
      // 输入框失去焦点以后隐藏
      inputDom.addEventListener("blur", () => {
        document.getElementById("set-model-detail").style.display = "none";
      });
    },
    // 点击保存按钮，保存当前数据建模信息
    handleSave() {
      // 检查JSON Schema中所有层级的title和description是否存在且不为空
      const isValid = this.jsonSchemaTool.checkTitlesAndDescriptions(this.jsonSchemaForm.jsonSchemaData);
      if (!isValid) {
        this.$message.error(
              this.$toolHandle.getI18nName(
                this.$zh.setup.responseText,
                this.$en.setup.responseText,
                this.$i18n.locale,
                "titleAnddescriptionCheck"
              )
            );
        return;
      }
      let referencedIds = this.getReferencedIds(
        this.jsonSchemaForm.jsonSchemaData
      );
      
      if (this.isAddModelData) {
        addModelData({
          ...this.jsonSchemaForm,
          jsonSchemaData: JSON.stringify(this.jsonSchemaForm.jsonSchemaData),
          quoteModelDataId: referencedIds.referencedIds,
          quoteGlobalModelDataId: referencedIds.globalReferencedIds,
        }).then((response) => {
          if (response.code == 200) {
            this.$message.success(
              this.$toolHandle.getI18nName(
                this.$zh.setup.responseText,
                this.$en.setup.responseText,
                this.$i18n.locale,
                "success"
              )
            );
            const newNodeId = response.data;
            this.$emit("refresh", newNodeId);
          }
        });
      } else {
        updateModelData({
          ...this.jsonSchemaForm,
          jsonSchemaData: JSON.stringify(this.jsonSchemaForm.jsonSchemaData),
          quoteModelDataId: referencedIds.referencedIds,
          quoteGlobalModelDataId: referencedIds.globalReferencedIds,
        }).then((response) => {
          if (response.code == 200) {
            this.$message.success(
              this.$toolHandle.getI18nName(
                this.$zh.setup.responseText,
                this.$en.setup.responseText,
                this.$i18n.locale,
                "success"
              )
            );
            this.$emit("refresh");
          }
        });
      }
    },
    // 点击删除按钮，删除当前未新增或已存在的数据建模
    handleDelete() { },
  },
};
</script>

<style lang="scss" scoped>
.title-input::placeholder {
  font-size: 20px;
}

.jsonSchema-detail {
  position: relative;
  width: 256px;
  height: 100%;
  min-width: 0;
  flex-grow: 1;
  flex-shrink: 1;
  display: flex;
  background-color: var(--ui-component-background);

  .jd-main {
    overflow: auto;

    .jd-main-container {
      height: 100%;
      overflow-y: auto;

      .jd-m-c-box {
        padding: 0px 20px;

        .form-wrap {
          width: 100%;
          position: relative;
          background-color: var(--ui-component-background);

          .title-compose {
            height: 32px;
            font-weight: 600;
            white-space: nowrap;
            text-overflow: ellipsis;
            flex: 1;
            padding: 0;
            font-size: 23px;
            line-height: 32px;
            overflow: hidden;
            border-bottom: 2px solid var(--ui-border-color-split);
            box-sizing: border-box;
            cursor: text;
          }

          .actions-wrap {
            margin-left: 16px;
            gap: 8px;
            display: inline-flex;
            align-items: center;
          }

          .jd-m-c-b-actions {
            flex-direction: row;
            width: 100%;
            min-height: 24px;
            margin-top: 6px;
            gap: 4px;

            span {
              color: var(--ui-breadcrumb-base-color);
            }

            .visible-way {
              padding: 2px 5px;
              border-radius: 6px;
              cursor: pointer;

              &:hover {
                background-color: var(--ui-input-filled-hover-bg);
              }
            }
          }

          .set-model-detail {
            border-bottom: 1px solid var(--ui-variant-btn-border-color);
            margin-top: 6px;
            margin-bottom: 0;
            transition: all 0.3s ease-in-out;
          }
        }

        .jsonschema-main-title{
          position: sticky;
          top: 0;
          z-index: 100;
          height: 120px;
          border-radius: 6px;
          padding: 10px 10px 0 10px;
          background-color: var(--ui-component-background-alt);
        }

        .jsonschema-main-content {
          min-width: 350px;
          border: 1px solid var(--ui-border-color-split);
          border-radius: 6px;

          .js-m-c-header {
            gap: 0 4px;
            padding: 7px 12px;
            border-bottom: 1px solid var(--ui-border-color-split);
          }

          .jsonschema-box {
            padding: 11px;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.set-alias-content {
  padding: 12px !important;
  box-sizing: border-box;

  p {
    border: 1px solid var(--ui-border-color-split);
    border-radius: 12px;
    padding: 12px;
    margin-bottom: 12px;
    margin-top: 0;
  }

  .set-alias-btns {
    margin-top: 12px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 4px;
  }
}

.title-input {
  flex: 1;
  min-width: 0;
  height: 32px;
  color: var(--ui-text-color);
  font-weight: 600;
  font-size: 23px;
  line-height: 32px;
  position: relative;
  border-radius: 0;
  border-right-width: 1px;
  background-color: var(--ui-input-bg);
  border-color: transparent;
  outline: none;
  padding-inline: 0;
  padding-block: 0;
}

.jsonschema-card {
  &.el-tabs--card .el-tabs__header {
    height: 48px;

    .el-tabs__nav {
      height: 48px;

      .el-tabs__item {
        height: 48px;
      }
    }
  }
}

.jsonschema-input {

  & .el-input__inner,
  & .el-input__inner:hover,
  & .el-input__inner:focus {
    border: none;
    outline: none;
    font-size: 23px;
    line-height: 32px;
    font-weight: 600;
  }
}

.jsonschema-btn {
  &.el-button {
    color: var(--ui-breadcrumb-base-color);
    text-align: left;
    font-size: 12px;
    padding: 1px 7px;
    line-height: 18px;
    border-radius: 6px;
    background-color: var(--ui-item-hover-bg);
    border-color: transparent;

    &:focus,
    &:hover {
      cursor: pointer;
      border-color: transparent;
      outline: none;
      color: var(--ui-breadcrumb-base-color);
      background-color: var(--ui-jsonschema-btn-color-hover);
    }
  }
}

.jtyj-set-mode-detail-input {
  .el-textarea__inner {
    border: none;
    border-radius: 0;
    font-size: 14px;
    font-weight: normal;
    padding: 0;
    overflow-y: hidden;
    height: 22px;
    resize: none;
    min-height: 22px;
    max-height: 110px;
    background: transparent;
  }
}
</style>